package com.furnitur.modules.portal.service.auth.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.furnitur.common.util.JwtTokenUtil;
import com.furnitur.core.entity.user.User;
import com.furnitur.core.mapper.user.UserMapper;
import com.furnitur.modules.portal.dto.auth.PortalLoginDTO;
import com.furnitur.modules.portal.dto.auth.PortalRegisterDTO;
import com.furnitur.modules.portal.service.auth.PortalAuthService;
import com.furnitur.modules.portal.vo.auth.PortalUserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Slf4j
@Service
public class PortalAuthServiceImpl implements PortalAuthService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    @Transactional
    public PortalUserVO register(PortalRegisterDTO dto) {
        // 验证密码匹配
        if (!dto.getPassword().equals(dto.getConfirmPassword())) {
            throw new RuntimeException("两次输入的密码不一致");
        }

        // 验证用户名是否存在
        if (checkUsernameExists(dto.getUsername())) {
            throw new RuntimeException("账号已被注册");
        }

        // 验证手机号是否存在
        if (checkPhoneExists(dto.getPhone())) {
            throw new RuntimeException("手机号已被注册");
        }

        // 验证邮箱是否存在
        if (checkEmailExists(dto.getEmail())) {
            throw new RuntimeException("邮箱已被注册");
        }

        // 创建用户
        User user = new User();
        user.setUsername(dto.getUsername());
        user.setPassword(passwordEncoder.encode(dto.getPassword()));
        user.setPhone(dto.getPhone());
        user.setEmail(dto.getEmail());
        user.setRoleId(3L);
        user.setStatus(1);
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());
        user.setAvatar(null);

        try {
            userMapper.insert(user);
            
            // 生成token
            String token = jwtTokenUtil.generateToken(user.getUsername());
            
            // 返回用户信息
            return createPortalUserVO(user, token);
        } catch (Exception e) {
            log.error("用户注册失败", e);
            throw new RuntimeException("注册失败，请稍后重试");
        }
    }

    @Override
    public PortalUserVO login(PortalLoginDTO dto) {
        // 查询用户
        User user = userMapper.selectOne(new QueryWrapper<User>()
                .eq("username", dto.getUsername()));
                
        // 验证用户存在
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 验证是否是会员用户
        if (!user.getRoleId().equals(3L)) {
            throw new RuntimeException("非会员用户，请使用正确的登录入口");
        }
        
        // 验证密码
        if (!passwordEncoder.matches(dto.getPassword(), user.getPassword())) {
            throw new RuntimeException("密码错误");
        }
        
        // 验证用户状态
        if (user.getStatus() != 1) {
            throw new RuntimeException("账号已被禁用");
        }
        
        // 生成JWT token
        String token = jwtTokenUtil.generateToken(user.getUsername());
        
        // 返回用户信息
        PortalUserVO vo = new PortalUserVO();
        vo.setId(user.getId());
        vo.setUsername(user.getUsername());
        vo.setPhone(user.getPhone());
        vo.setEmail(user.getEmail());
        vo.setRoleId(user.getRoleId());
        vo.setStatus(user.getStatus());
        vo.setAvatar(user.getAvatar());
        vo.setToken(token);  // 设置JWT token
        
        return vo;
    }

    private boolean checkUsernameExists(String username) {
        return userMapper.selectCount(new QueryWrapper<User>()
                .eq("username", username)) > 0;
    }

    private boolean checkPhoneExists(String phone) {
        return userMapper.selectCount(new QueryWrapper<User>()
                .eq("phone", phone)) > 0;
    }

    private boolean checkEmailExists(String email) {
        return userMapper.selectCount(new QueryWrapper<User>()
                .eq("email", email)) > 0;
    }

    private PortalUserVO createPortalUserVO(User user, String token) {
        PortalUserVO vo = new PortalUserVO();
        vo.setId(user.getId());
        vo.setUsername(user.getUsername());
        vo.setPhone(user.getPhone());
        vo.setEmail(user.getEmail());
        vo.setRoleId(user.getRoleId());
        vo.setStatus(user.getStatus());
        vo.setAvatar(user.getAvatar());
        vo.setToken(token);
        return vo;
    }
} 